/* components */
import { ConnectorListViewHeader, ConnectorListViewCard, ConnectorListViewCreateDialog, ConnectorListViewHeaderView, ConnectorListViewTableIndex } from '@src/modules/connector/view/list/components'
import { ConnectorListViewHeaderButtonType } from '@src/modules/connector/view/list/components/header'
import BaseChange from '@src/modules/connector/view/list/components/baseChange/index.tsx'
import CreateTriggerDialog from '@src/modules/trigger/components/CreateTriggerDialog'
import { Notification, Button } from 'element-ui'
/* hooks */
import { useConnectListDialog, useConnectorList } from '@src/modules/connector/view/list/hooks'
import { useDialog } from '@hooks/useDialog'
/* model */
import { ConnectorModuleComponentNameEnum } from '@src/modules/connector/model'
import { CreateConnectorFields } from '@src/modules/connector/view/list/model'
/* scss */
import '@src/modules/connector/view/list/index.scss'
/* vue */
// @ts-ignore
import { ComponentInstance, ComponentRenderProxy, computed, defineComponent, onBeforeMount, reactive, ref, toRefs } from 'vue'
import { CommonComponentInstance } from '@model/VC'
import { CreateElement } from 'vue'
import router from '@src/router'
/* util */
import { isFalse } from '@src/util/type'
import AuthUtil from '@src/util/auth';
import { openAccurateTab } from '@src/util/platform'
import { postPage } from 'pub-bbx-utils'
import { getRootWindow } from '@src/util/dom';
import { getAsyncSystemFrameInitData } from '@src/api/InitDataApi'
import { openTab } from '@src/platform'
// import { PageRoutesTypeEnum } from '@model/enum/PageRoutesEnum'
import { t } from '@src/locales';
/* types */
import { TriggerSettingCardItem } from '@src/modules/connector/types'

import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
/* api */
import * as TriggerApi from '@src/modules/connector/api/trigger'
import { message } from '@src/util/message'
import { debounce } from 'lodash'
/* enum */
import { AuthEnum } from "@src/modules/connector/model/enum"
/* state */
import state from '@src/modules/trigger/view/setting/util/state.js'

export type ConnectorListViewProps = {
  
}

export interface ConnectorListViewSetupState {
  
}

export enum ConnectorListViewEmitEventNameEnum {
  Input = 'input',
}


export type ConnectorListViewInstance = ComponentInstance & ConnectorListViewSetupState
export type ConnectorListViewVM = ComponentRenderProxy<ConnectorListViewProps> & CommonComponentInstance & ConnectorListViewInstance

export default defineComponent({
  name: ConnectorModuleComponentNameEnum.ConnectorListView,
  emits: [
    ConnectorListViewEmitEventNameEnum.Input,
  ],
  props: {
    
  },
  setup(props: ConnectorListViewProps, { emit }) {
    let searchParams = {}
    try {
      // API设置获取触发器列表需要传appId
      searchParams = Object.fromEntries(new URLSearchParams(location.search).entries()) || {}
    } catch (error) {
      console.warn(error)
    }
    const params = ref({
      appId: searchParams.appId,
      from: searchParams.from || '',
      triggerList: searchParams.triggerList || '',
      query:'',
      bizType:'',
      bizTypeId:'',
      bizActionCode:'',
      pageSize:9999,
      pageNum:1,
    })
    const auth = ref([] as any[]);
    const authType = reactive({
      isCreate: false,
      isEdit: false,
      isDelete: false,
    })
    const loadings = ref(false)
    // list / card 两种类型
    let toggleShow =  ref('list')
    const auths = ref({});

    const { initialize, connectorList, onDeleteConnectorHandler, onEditConnectorHandler,fetchConnectorListLoading } = useConnectorList(params.value)
    
    const { dialogTitle, formValue, resetFormValue, setFormValue, setIsCreateConnector } = useConnectListDialog()
    
    const { visible, showDialog, hideDialog } = useDialog()
    
    const initializeDebounceHandler = debounce(initialize, 500)

    const inputKeyword = (keyword: string) => {
      params.value.query = keyword
      initializeDebounceHandler()
    }
    // 权限控制
    function getAuthByRootInitData() {
      const rootWindow = getRootWindow(window)
      const _initData = JSON.parse(rootWindow?._init || '{}')
      auths.value = _initData?.user?.auth || {}
      authType.isCreate = AuthUtil.hasAuth(auths.value, AuthEnum.trigger_view);
      authType.isDelete = AuthUtil.hasAuth(auths.value, AuthEnum.trigger_delete);
      authType.isEdit = AuthUtil.hasAuth(auths.value, AuthEnum.trigger_edit);
      if(_initData) {
        loadings.value = true
      }
    }
    
    getAuthByRootInitData()
    const onDialogCloseHandler = () => {
      hideDialog()
    }
    
    const handleSearch = ()=>{
      initialize()
    }

    onBeforeMount(() => {
      initialize()
    })

    const isNewTrigger = ref(router.currentRoute.path == '/trigger/design');
    
    return {
      connectorList,
      dialogTitle,
      formValue,
      params,
      toggleShow,
      auth,
      ...toRefs(authType),
      loadings,

      visible,
      showDialog,
      hideDialog,
      onDialogCloseHandler,
      
      resetFormValue,
      setFormValue,
      setIsCreateConnector,
      
      onDeleteConnectorHandler,
      onEditConnectorHandler,
      handleSearch,
      inputKeyword,
      fetchConnectorListLoading,
      isNewTrigger,
    }
    
  },
  methods: {
    async getTriggerUseCount() {
      try {
        const res = await TriggerApi.getTriggerUseMount()
        if (!res.success) {
          this.$message({ type: 'error', message: res.message })
          return false
        }
        if (res.data.used >= res.data.total) {
          this.dosageNotification({used: res.data.used, total: res.data.total})
          return false
        }
        return true
      } catch(error) {
        console.error(error)
      }
    },
    dosageNotification({used = 0, total = 0}) {
      const h = this.$createElement;
			Notification({
				customClass: 'isEnable-notification',
				type: 'info',
				title: t("trigger.tip.text1"),
				duration: 0,
				message: h('div', [
					h('p', { style: { marginTop: '16px' } }, `${t("trigger.tip.text2")} (${used}/${total})`),
					h('p', { style: { marginBottom: '16px' } }, t("trigger.tip.text3")),
					h(Button, {
						props: { type: 'primary' },
            on: { click: this.jumpContactUs }
					}, t("trigger.tip.text4"))
				]),
			});
		},
		jumpContactUs() {
			postPage({
        action: 'shb.system.openChat',
        data: {}
      })
		},
    /** 
     * @description 新建连接器事件
    */
    async onCreateConnectorHandler() {
      if(this.isCreate) {
        const res = await this.getTriggerUseCount()
      if (!res) return
      this.setIsCreateConnector()
        this.resetFormValue()
        if (this.isNewTrigger) {
          this.$refs.CreateTriggerDialog.showDialog();
        } else {
          this.showDialog();
        }
      } else {
        this.$message({
          message: t("trigger.authMessage"),
          type: 'error'
        });
      }
    },
    /** 
     * @description 更新连接器事件
    */
    onUpdateConnectHandler(connector: TriggerSettingCardItem) {
      this.setIsCreateConnector(false)
      this.setFormValue(connector)
      if (this.isNewTrigger) {
        // 新建触发器修改名称调用原来即可
        this.showDialog();
      } else {
        this.showDialog();
      }
    },
    /** 
     * @description 连接器弹窗新建/编辑事件（名称、描述）
    */
    onDialogConfirmHandler(info:any) {
      if(this.formValue.id){
        TriggerApi.updateTriggerStat({triggerId: this.formValue.id,triggerName:this.formValue.name,triggerDesc:this.formValue.description}).then((res:any)=>{
          if(res.status == 0){
            message.success(t('common.base.tip.modifySuccess'))
            this.handleSearch()
            this.hideDialog()
          }else{
            message.error(res.message)
          }
        })
      }else{
        let fromId = window.frameElement?.getAttribute('id');
        if(this.params.from === 'api' || this.params.from === 'auth') {
          // 从系统集成中心下的触发器列表或者第三方应用设置下面的触发器列表过来   
          fromId = window?.parent?.frameElement?.getAttribute('id')
        }
        if (this.isNewTrigger) {
          this.openEditNewTab(this.formValue);
        } else {
          openAccurateTab({
            type: PageRoutesTypeEnum.PageConnectorSetting,
            params: `name=${encodeURIComponent(this.formValue.name)}&description=${encodeURIComponent(this.formValue.description)}&from=${this.params.from}`,
            fromId
          })
        }
        this.hideDialog()
      }
    },
    /** 
     * @description 连接器弹窗更新事件（名称、描述）
    */
    onDialogUpdateHandler(info:any) {
      let { fieldName,newValue } = info
      if( !fieldName )return;
      this.formValue[fieldName] = newValue
    },

    resetSearch(){
      if(this.params.query){
        this.params.query = ''
        this.handleSearch()
      }
    },

    onLogConnectorHandler(connector: TriggerSettingCardItem) {

      const fromId = window.frameElement.getAttribute('id') || ''

      openAccurateTab({
        type: PageRoutesTypeEnum.TriggerPageCallLog,
        params: `triggerNo=${connector.id}`,
        fromId
      })
    },
    clickChangeStatus(item: string) {
      this.toggleShow = item
      if (item === 'list') {
        this.$refs.ConnectorListView.$el.classList.add('list')
        this.$refs.ConnectorListView.$el.classList.remove('card')
      } else if (item === 'card'){
        this.$refs.ConnectorListView.$el.classList.remove('list')
        this.$refs.ConnectorListView.$el.classList.add('card')
      }
    },
    onDialogSubmitHandler(formValue) {
      const fromId = window.frameElement.getAttribute('id') || ''
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTriggerDesign,
        params: `name=${formValue.value.name}&triggerWay=${formValue.value.triggerWay}&desc=${formValue.value.des}`,
        fromId
      })
      this.$refs.CreateTriggerDialog.closeDialog();
    },
    openEditNewTab(value) {
      const fromId = window.frameElement.getAttribute('id') || ''
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTriggerDesign,
        params: `triggerId=${value.id}`,
        titleKey: value.triggerName,
        key: `${value.id}`,
        fromId
      })
    },
  },
  render(h: CreateElement) {
  return (
      <div class={ConnectorModuleComponentNameEnum.ConnectorListView}>
        {
          this.params.triggerList === '' && <ConnectorListViewHeaderView isNewTrigger={this.isNewTrigger}/>
        }
        
        <div class="cardList">
          <ConnectorListViewHeader
            title={t('common.connector.title.trigger')}
            subTitle={t('common.connector.subTitle.title1')}
            buttons={this.connectorListHeaderButtons}
            ref={"ConnectorListView"}
          >

            <div slot={'right'}>
              <div class="customer-list-base-search-group input-with-append-search">
                <el-input value={this.params.query} placeholder={t('common.connector.trigger.searchByNo')}
                          class="mar-r-12" style={{ width: '300px' }} onInput={this.inputKeyword}>
                  <i slot="prefix" class="el-input__icon el-icon-search"></i>
                  { <el-button
                    type="primary"
                    slot="append"
                    onClick={this.handleSearch}
                    native-type="submit"
                  >{t("common.base.search")}</el-button> }
                </el-input>
                {/* <el-button type="plain-third" onClick={()=>{this.resetSearch()}}>重置</el-button> */}
                {/* 切换状态 */}
                <BaseChange onChange={(item) => this.clickChangeStatus(item)} value={this.toggleShow}/>
              </div>
            </div>

            <div slot={'left'}>
              <el-button
                v-show={this.loadings}
                type="primary"
                onClick={this.onCreateConnectorHandler}
              >
                {/* <i class="iconfont icon-add2">
                </i> */}
                {t('common.base.create')}
              </el-button>
            </div>
          </ConnectorListViewHeader>
          <div v-show={this.toggleShow === 'card'}>
            <ConnectorListViewCard
              edit={this.isEdit}
              delete={this.isDelete}
              value={this.connectorList}
              onDelete={this.onDeleteConnectorHandler}
              onEdit={this.isNewTrigger? this.openEditNewTab : this.onEditConnectorHandler}
              onUpdate={this.onUpdateConnectHandler}
              onLog={this.onLogConnectorHandler}
              loading={this.fetchConnectorListLoading}
                >
            </ConnectorListViewCard>
          </div>
          <div v-show={this.toggleShow === 'list'}>
            {/* {this.loadings && (
              <ConnectorListViewTableIndex 
                edit={this.isEdit}
                delete={this.isDelete}
                value={this.connectorList} 
                loading={this.fetchConnectorListLoading}
                onDelete={this.onDeleteConnectorHandler}
                onEdit={this.onEditConnectorHandler}
                onUpdate={this.onUpdateConnectHandler}
                onLog={this.onLogConnectorHandler}
              />
            )} */}
            <ConnectorListViewTableIndex 
                edit={this.isEdit}
                delete={this.isDelete}
                value={this.connectorList} 
                loading={this.fetchConnectorListLoading}
                onDelete={this.onDeleteConnectorHandler}
                onEdit={this.isNewTrigger? this.openEditNewTab : this.onEditConnectorHandler}
                onUpdate={this.onUpdateConnectHandler}
                onLog={this.onLogConnectorHandler}
              />
          </div>

        </div>

        <ConnectorListViewCreateDialog
          title={this.dialogTitle}
          value={this.formValue}
          visible={this.visible}
          fields={CreateConnectorFields}
          onClose={this.onDialogCloseHandler}
          onConfirm={this.onDialogConfirmHandler}
          onInput={this.onDialogUpdateHandler}
        >
        </ConnectorListViewCreateDialog>

        <CreateTriggerDialog
          ref='CreateTriggerDialog'
          onSubmit={this.onDialogSubmitHandler}
        >
        </CreateTriggerDialog>
      </div>
    )
  }
})
